package com.longtop.perform.khyg.service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.longtop.framework.base.BaseService;
import com.longtop.framework.common.Constant;
import com.longtop.framework.security.BaseCheckedException;
import com.longtop.framework.security.SessionObject;
import com.longtop.framework.util.ReflectUtil;
import com.longtop.framework.util.StringUtil;
import com.longtop.framework.util.UniqueKeyUtil;
import com.longtop.perform.khyg.model.TKhygIndex;
import com.longtop.perform.khyg.model.TKhygIndexData;
import com.longtop.perform.khyg.model.TKhygProject;
import com.longtop.perform.khyg.model.TKhygSegment;
import com.longtop.perform.khyg.model.TKhygSegmentMx;
import com.longtop.perform.khyg.model.TKhygTask;
import com.longtop.perform.khyg.model.TKhygTaskMx;

/**
 * 
 * @author 孙景弘
 * 
 */
public class ProjectService extends BaseService {

	public static final String BEAN_ID = "projectService";

	/**
	 * 新增/修改考核方案（包括方案分段，与方案对应的指标）
	 * 
	 * @param project
	 * @param projectIndexs
	 * @param projectSegment
	 * @param task
	 *            是新增还是修改，update:修改
	 * @throws BaseCheckedException
	 */
	public void saveProject(TKhygProject project, List projectIndexs, List projectSegment, String task, SessionObject sessionObject) throws BaseCheckedException {
		String projectId = project.getProjectId();
		Iterator iterator;
		if ("update".equals(task)) {
			this.setAuthPropetryToEntity(project, sessionObject, false); // 设置权限属性
			this.update(project);// 修改考核方案
			// 删除原考核方案对应指标：
			this.deleteAll(this.queryAll("from TKhygIndex where projectId='" + projectId + "'"));

			// 更新考核方案-对应阶段的进度状态（计算成绩为0，评分模型为0）
			List<TKhygSegment> segmentList = this.queryAll("from TKhygSegment where projectId = '" + projectId + "'");
			if (segmentList.size() > 0) {
				for (TKhygSegment khygSegment : segmentList) {
					this.updateSegmentStatus(TKhygSegment.class, khygSegment.getSegmentId(), 2, false);
					this.updateSegmentStatus(TKhygSegment.class, khygSegment.getSegmentId(), 6, false);
				}
			}

		} else {
			if (isExistProjectId(projectId))// 校验id是否重复。
				throw new BaseCheckedException("", "保存失败,考核方案id【" + projectId + "】已经存在!");

			projectId = UniqueKeyUtil.getUuidKey();
			project.setProjectId(projectId);
			this.setAuthPropetryToEntity(project, sessionObject, true); // 设置权限属性
			this.save(project);// 保存考核方案
			this.getHibernateTemplate().flush();

			// 保存方案分段:
			if (projectSegment.size() > 0) {
				iterator = projectSegment.iterator();
				TKhygSegment segment;
				while (iterator.hasNext()) {
					segment = (TKhygSegment) iterator.next();
					segment.setProjectId(projectId);
					segment.setStatus("10000000");
					segment.setSegmentName(project.getProjectName() + "_" + segment.getCycleId());
					this.save(segment);
				}
			} else {// 无分段则也新增一条记录（分段字段为空）
				TKhygSegment segment = new TKhygSegment();
				segment.setProjectId(projectId);
				segment.setStatus("10000000");
				segment.setSegmentName(project.getProjectName() + "_" + project.getCycleId());
				segment.setStartDate(project.getStartDate());
				segment.setEndDate(project.getEndDate());
				this.save(segment);
			}
		}

		// 保存方案对应的指标:
		if (projectIndexs.size() > 0) {
			iterator = projectIndexs.iterator();
			TKhygIndex projectIndex;
			while (iterator.hasNext()) {
				projectIndex = (TKhygIndex) iterator.next();
				projectIndex.setProjectId(projectId);
				projectIndex.setScoreModeId("0");
				this.save(projectIndex);
			}
		}

	}

	/**
	 * 验证projectId 是否存在
	 * 
	 * @param projectId
	 * @return
	 */
	private boolean isExistProjectId(String projectId) {
		List list = this.queryAll("from TKhygProject where projectId='" + projectId + "'");
		return list.size() > 0;
	}

	/**
	 * 获取考核方案对应分段
	 * 
	 * @param projectId
	 * @return
	 */
	public List getProjectSegment(String projectId) {
		TKhygProject userProject = this.get(TKhygProject.class, projectId);
		// 判断是否有分段：
		if (StringUtil.isEmpty(userProject.getSegmentType())) {
			return this.queryAll("from TKhygSegment where projectId = '" + projectId + "'");
		} else {
			return this.queryForListByIbatis("khygProjectSql.queryProjectSegment", projectId);
		}
	}

	/**
	 * 提交保存考核阶段对应员工和任务对应员工
	 * 
	 * @param changeMap
	 * @param segmentId
	 *            考核阶段Id
	 * @param segmentName
	 *            考核阶段名称
	 * @param indexList
	 *            考核方案对应定量指标
	 * @return
	 */
	public Integer[] saveSegmentUser(Map changeMap, String segmentId, String segmentName, List indexList, SessionObject sessionObject) {
		int insertCount = 0;
		int updateCount = 0;
		int deleteCount = 0;
		List insertBeanList = (ArrayList) changeMap.get(Constant.INSERT_BEAN_LIST);
		String idList = (String) changeMap.get(Constant.ID_LIST);
		List deleteBeanList = (ArrayList) changeMap.get(Constant.DELETE_BEAN_LIST);

		TKhygSegmentMx segmentUser = new TKhygSegmentMx();// C
		Iterator iterator;

		// 批量插入记录
		if (insertBeanList.size() > 0) {
			iterator = insertBeanList.iterator();
			while (iterator.hasNext()) {
				// 保存阶段对应员工：
				segmentUser = (TKhygSegmentMx) iterator.next();

				// 校验此阶段是否已经包含员工
				List list = this.queryAll("from TKhygSegmentMx where userId='" + segmentUser.getUserId() + "' and segmentId='" + segmentUser.getSegmentId() + "'");
				if (list.size() > 0) {
					continue;
				}

				String uuid = UniqueKeyUtil.getUuidKey();
				segmentUser.setId(uuid);
				super.save(segmentUser);

				// 保存任务对应员工：
				TKhygTask userTask = new TKhygTask();
				userTask.setTaskId(uuid);
				userTask.setTaskName(segmentName + "_" + segmentUser.getUserName());// 任务名称=考核阶段名称+员工姓名
				userTask.setSegmentId(segmentUser.getSegmentId());
				userTask.setUserId(segmentUser.getUserId());
				super.save(userTask);

				// 保存任务员工明细(定量指标)：
				for (int i = 0; i < indexList.size(); i++) {
					Map indexMap = (Map) indexList.get(i);
					String indexType = indexMap.get("indexType").toString();
					if (!"1".equals(indexType)) {
						TKhygTaskMx userTaskMx = new TKhygTaskMx();
						userTaskMx.setSegmentId(segmentId);
						userTaskMx.setTaskId(uuid);
						userTaskMx.setUserId(segmentUser.getUserId());
						userTaskMx.setIndexId(indexMap.get("indexId").toString());
						super.save(userTaskMx);
					}
				}

				// 添加员工-定性指标数据：
				for (int i = 0; i < indexList.size(); i++) {
					Map indexMap = (Map) indexList.get(i);
					String indexType = indexMap.get("indexType").toString();
					if ("1".equals(indexType)) {
						TKhygIndexData userIndexData = new TKhygIndexData();
						userIndexData.setSegmentId(segmentId);
						userIndexData.setUserId(segmentUser.getUserId());
						userIndexData.setIndexId(indexMap.get("indexId").toString());
						userIndexData.setIndexType(indexType);
						this.setAuthPropetryToEntity(userIndexData, sessionObject, true);// 设置权限属性
						super.save(userIndexData);
					}
				}

				insertCount++;
			}
		}
		// 批量删除记录//C
		if (idList.length() > 0) {
			// 删除阶段对应员工：
			String sql = "delete from TKhygSegmentMx where id in(" + idList + ")";
			deleteCount = super.batchUpdate(sql);

			// 删除任务对应员工：
			String taskDelSql = "delete from TKhygTask where id in(" + idList + ")";
			super.batchUpdate(taskDelSql);

			// 删除任务员工明细：
			String taskMxDelsql = "delete from TKhygTaskMx where taskId in(" + idList + ")";
			super.batchUpdate(taskMxDelsql);

			// 删除员工-定性指标数据：
			// 构建删除记录的的员工id
			StringBuffer userIdBuffer = new StringBuffer();
			if (deleteBeanList.size() > 0) {
				iterator = deleteBeanList.iterator();
				while (iterator.hasNext()) {
					segmentUser = (TKhygSegmentMx) iterator.next();
					StringUtil.populate(userIdBuffer, segmentUser.getUserId(), iterator.hasNext());
				}
			}
			String userIdList = StringUtil.afterOfDeletion(userIdBuffer.toString(), ",");

			String indexDataDelsql = "delete from TKhygIndexData where segmentId = '" + segmentId + "' and userId in(" + userIdList + ")";
			super.batchUpdate(indexDataDelsql);
		}

		// 判断删除操作完之后：考核分段对应的USER是否还存在记录：>>修改相应考核分段表的进度状态
		List list = this.queryAll("from TKhygSegmentMx where segmentId = '" + segmentId + "'");
		boolean statusFlag = list.size() > 0 ? true : false;
		this.updateSegmentStatus(TKhygSegment.class, segmentId, 3, statusFlag);
		if (!statusFlag) {
			this.updateSegmentStatus(TKhygSegment.class, segmentId, 4, statusFlag);
			this.updateSegmentStatus(TKhygSegment.class, segmentId, 5, statusFlag);
		}
		this.updateSegmentStatus(TKhygSegment.class, segmentId, 6, false);// 计算成绩状态为0

		return new Integer[] { new Integer(insertCount), new Integer(updateCount), new Integer(deleteCount) };
	}

	/**
	 * 全部删除考核阶段对应员工
	 * 
	 * @param segmentId
	 *            考核分段ID主键
	 */
	public void deleteAllSegmentUser(String segmentId) {
		// 删除阶段对应员工：
		String sql = "delete from TKhygSegmentMx where segmentId = '" + segmentId + "'";
		super.batchUpdate(sql);

		// 删除任务对应员工：
		String taskDelSql = "delete from TKhygTask where segmentId = '" + segmentId + "'";
		super.batchUpdate(taskDelSql);

		// 删除任务员工明细：
		String taskMxDelsql = "delete from TKhygTaskMx where  segmentId = '" + segmentId + "'";
		super.batchUpdate(taskMxDelsql);

		// 删除员工-定性指标数据：
		String indexDataDelsql = "delete from TKhygIndexData where segmentId = '" + segmentId + "'";
		super.batchUpdate(indexDataDelsql);

		// 修改相应考核分段表的进度状态:
		this.updateSegmentStatus(TKhygSegment.class, segmentId, 3, false);
		this.updateSegmentStatus(TKhygSegment.class, segmentId, 4, false);
		this.updateSegmentStatus(TKhygSegment.class, segmentId, 5, false);

	}

	/**
	 * 更新考核分段的状态：初始状态为8个0；每完成一步则设置为1
	 * 
	 * @param segmentClass
	 *            传入员工segmentClass或则机构segmentClass
	 * @param segmentId
	 *            考核分段ID主键
	 * @param projectStep
	 *            需要修改第几步的状态
	 * @param stautsFlag
	 *            需要修改状态的值：false-未完成-'0'，true-完成-'1'
	 */
	public void updateSegmentStatus(Class segmentClass, Serializable segmentId, int projectStep, boolean stautsFlag) {
		Object projectSegment = super.get(segmentClass, segmentId);

		String status = "" + ReflectUtil.getFieldValue(projectSegment, "status");
		char[] charArray = status.toCharArray();
		char stautsValue = stautsFlag ? '1' : '0';
		charArray[projectStep - 1] = stautsValue;
		status = new String(charArray);
		ReflectUtil.setFieldValue(projectSegment, "status", String.class, status);
		super.update(projectSegment);
	}

	/**
	 * 获取考核分段的状态：初始状态为8个0；每完成一步则设置为1
	 * 
	 * @param segmentClass
	 *            传入员工segmentClass或则机构segmentClass
	 * @param segmentId
	 *            考核分段ID主键
	 * @param projectStep
	 *            需要修改第几步的状态
	 * @return 对应第几步的状态的值：false-未完成-'0'，true-完成-'1'
	 */
	public boolean getSegmentStatus(Class segmentClass, Serializable segmentId, int projectStep) {
		Object projectSegment = super.get(segmentClass, segmentId);
		String status = "" + ReflectUtil.getFieldValue(projectSegment, "status");
		boolean flag = String.valueOf(status.charAt(projectStep - 1)).equals("0") ? false : true;
		return flag;
	}
}